package com.example.myapplication2;

import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class SpinnerActivity extends AppCompatActivity implements  AdapterView.OnItemSelectedListener {

    private Spinner spinner_dialog;
    private Spinner spinner_dropdown;
    public static final String[] array={"Q","A","B"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner);
        spinner_dialog = findViewById(R.id.Spinner_dialog);
        spinner_dropdown = findViewById(R.id.Spinner_dropdown);
//        声明一个下拉适配器
        ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<>(this, R.layout.spinner_item_select, array);
        //设置适配器
        spinner_dialog.setAdapter(stringArrayAdapter);
        spinner_dropdown.setAdapter(stringArrayAdapter);
        //设置spinner_dialog的标题
        spinner_dialog.setPrompt("spinner_dialog的标题");
        //设置默认显示
        spinner_dialog.setSelection(0);
        spinner_dropdown.setSelection(0);
        //设置监听
        spinner_dialog.setOnItemSelectedListener(this);
        spinner_dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(SpinnerActivity.this,array[i],Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        Toast.makeText(this,array[i],Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}